var http = require('http')
var spawn = require('child_process').spawn
var createHandler = require('github-webhook-handler')
// 在代码仓库的 Webhooks 选项处配置
var handler = createHandler({ path: '/pushCode', secret: 'mysql' }) 
const script = '/home/ubuntu/test/auto/messagepublish/auto.sh';
const currentPath = '/home/ubuntu/test/tec-message-publish';
http.createServer(function (req, res) {
  console.log('接受到请求', req.headers);
 handler(req, res, function (err) {
  if(req.headers['x-gitee-token'] === 'mysql') {
    console.log('密码正确 开始拉取代码');
    rumCommand('sh', [script], function( txt ) { // 执行 autoBuild.sh 脚本文件
      console.log('执行了脚本')
      console.log(txt);
      console.log('执行结束');
    });
    res.statusCode = 200;
    res.end('success');
  } else {
    res.statusCode = 200;
    res.end('???');
  }
 })
}).listen(3000);
console.log('listen to 127.0.0.1:3000')
 
handler.on('error', function (err) {
 console.error('Error:', err.message)
})
 
// // 监听 push 事件
// handler.on('push', function (event) {
//  console.log('Received a push event for %s to %s',
//   event.payload.repository.name,
//   event.payload.ref)
//  rumCommand('sh', ['./autoBuild.sh'], function( txt ) { // 执行 autoBuild.sh 脚本文件
//   console.log(txt)
//  })
// })
 
function rumCommand( cmd, args, callback ) {
  var child = spawn( cmd, args, {
    cwd: currentPath,
  } )
  var response = ''
  child.stdout.on('data', function( buffer ){ response += buffer.toString(); })
  child.stdout.on('end', function(){ callback( response ) })
}